<template>
    <admin-container :loading="loading">
        <k-form ref="form"
                 :model="form"
                 label-width="120px"
                 @submit.prevent.native="onSubmit">
            <k-form-item label="头像"
                          prop="avatar"
                          :rules="[
                              { required: true, message: '请上传头像' }
                          ]">
                <k-input-upload v-model="form.avatar"
                                @input="onUploadAvatar('avatar', $event)"
                                :multi="false"/>
            </k-form-item>

            <k-form-item label="用户名"
                          prop="username"
                          :rules="[
                              { required: true, message: '请填写用户名' }
                          ]">
                <el-input v-model="form.username" placeholder="清输入用户名"/>
            </k-form-item>

            <k-form-item label="称呼"
                          prop="nickname"
                          :rules="[
                              { required: true, message: '请填写称呼' }
                          ]">
                <el-input v-model="form.nickname" placeholder="清输入称呼"/>
            </k-form-item>

            <k-form-item label="手机号码"
                          prop="phone"
                          :rules="[
                              { required: true, message: '请填写手机号码' }
                          ]">
                <el-input v-model="form.phone" placeholder="清输入手机号码"/>
            </k-form-item>

            <k-form-item label="登陆密码"
                          prop="password"
                          :rules="id ? undefined : [
                              { required: true, message: '请填写登录密码' }
                          ]">
                <el-input v-model="form.password"
                          :type="id ? 'password' : 'text'"
                          :placeholder="id ? '如不修改留空即可' : '清输入登录密码'"/>
            </k-form-item>

            <k-form-item label="组织">
                <el-select v-model="form.department_id" placeholder="请选择">
                    <el-option :value="0" label="无"/>
                    <el-option
                        v-for="item in departments"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </k-form-item>

            <k-form-item label="角色"
                          v-if="!form.is_super"
                          prop="roles"
                          :rules="[
                              { required: true, message: '请选择角色' }
                          ]">
                <el-select v-model="form.roles" multiple placeholder="请选择">
                    <el-option
                        v-for="item in roles"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </k-form-item>

            <k-form-item>
                <el-button type="primary" native-type="submit" :loading="subing">保存</el-button>

            </k-form-item>
        </k-form>
    </admin-container>
</template>

<script lang="ts">
import { Vue, Component, Inject } from 'vue-property-decorator';
import AdminContainer from '@/components/admin-container.vue';
import KInputUpload from '@/components/input-upload.vue';
import { getSuperUser, saveSuperUser } from '@/services/auth/user.service';
import { getAuthRoles } from '@/services/auth/role.service';
import { getDepartments } from '@/services/auth/department.service';
import { AdminDepartmentModel } from '@/models/admin-department.model';
import SystemAclUsers from '../index.vue';
import KForm from '@/components/form/KForm.vue';
import KFormItem from '@/components/form/KFormItem.vue';

const initData = { sex: 0 };

@Component({
    components: { KFormItem, KForm, KInputUpload, AdminContainer }
})
export default class Page extends Vue {
    @Inject() readonly root!: SystemAclUsers;
    form: any = { ...initData };
    loading: boolean = true;
    subing: boolean = false;
    roles: any[] = [];
    departments: AdminDepartmentModel[] = [];

    get id(): number {
        return Number(this.$route.query.id);
    }

    get title(): string {
        return this.id ? '编辑管理信息' : '添加管理';
    }

    mounted() {
        this.getDepartments();
        this.getRoles();
        if (this.id) {
            getSuperUser(this.id)
                .finally(() => {
                    this.loading = false;
                })
                .then(result => {
                    this.form = result.data;

                    this.$nextTick(() => {
                        (this.$refs.form as any).clearValidate();
                    });
                });
        } else {
            this.loading = false;

            this.$nextTick(() => {
                (this.$refs.form as any).clearValidate();
            });
        }
    }

    onUploadAvatar(field: string, value: any) {
        (this.$refs.form as any).validateField([field]);
    }

    /**
     * 获取组织列表
     */
    getDepartments() {
        getDepartments()
            .then(result => {
                this.departments = result.data.items;
            });
    }

    /**
     * 获取角色列表
     */
    getRoles() {
        getAuthRoles()
            .then(result => {
                this.roles = result.data.items;
            });
    }

    async onSubmit() {
        await this.$validator('form');
        this.subing = true;
        saveSuperUser(!!this.id, this.form)
            .finally(() => {
                this.subing = false;
            })
            .then((result) => {
                this.form = result.data;
                if (!this.id) {
                    this.form = { ...initData };
                    this.$router.replace({ query: { id: result.data.id } });
                }
                this.$message.success('保存成功');
            });

    }

}
</script>
